<!--
* description:
* author: hezm
* createdDate: 2021-1-27
-->

<template>
  <div class="app-container app-container-table">
    <!-- :key="oneTableKey" -->
    <one-table-template
      ref="multipleTable"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="dynamicApiConfigs"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-select="true"
      :dynamic-is-init-table="true"
      :dynamic-api-style="'restful'"
      :callbackObj="callbackObj"
    />

    <edit
      :key="editPopupsKey"
      :dynamic-edit-row-data="editRowData"
      :popups-visible="editPopupsVisible"
      :codeOpenList="codeOpen"
      :popups-state="editPopupsState"
      :dynamic-api-style="'restful'"
      @close="close"
    />
  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from "@/components/mixins/oneTableWithViewTemplateMixins";
import OneTableTemplate from "@/components/templates/oneTable";
import Vue from "vue";
import { orgApis } from "@/api/paSparePartsManagement";

export default {
  name: "shortageRegistration",

  components: {
    OneTableTemplate,
    Edit: () => import("./edit")
  },
  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins],

  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, ""], function() {
      next();
    });
  },

  data() {
    // this.$refs['multipleTable'].data = [{bigAreaCode:'1'}]
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path;

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode]);

    return {
      callbackObj: {
        onCheckSelectChange: selection => {
          this.selectdatas = selection;
          console.log(selection);
        }
      },
      selectdatas: [],
      codeOpen: 1,
      editRowData: {},
      // 网格查询API配置对象
      // apiConfig: {
      //   ServiceCode: 'queryBigArea',
      //   APIUrl: '/mp/e3sh/basics/ve/bigareaService/queryBigArea.do'
      // },
      dynamicApiConfigs: orgApis.getQueryList,

      // 动态组件-按钮
      tableButtons: [
        {
          compKey: "btnKey1",
          type: "primary",
          size: "small",
          name: "search",
          clickEvent: () => this.queryTable(1),
          text: this.$t("sys.button.query"), // 查询
          position: "right",
          fuzzySearch: true
        },
        {
          compKey: "btnKey3",
          type: "",
          size: "small",
          name: "add",
          clickEvent: this.add,
            // debugger
            // this.editRowData = {}
            // this.editPopupsKey = 'key' + this.$utils.generateId()
            // this.editPopupsVisible = true

          // text: this.$t('sys.button.add'), // 新增
          text: "新增",
          position: "left"
        },

        {
          compKey: "btnKey2",
          labelName: "作废",
          size: "small",
          name: "importTemplate",
          icon: "iconfont icon-importTemplate",
          clickEvent: () => {

            this.$confirm('确定要作废吗?', '提示', {
              type: 'warning'
            }).then(() => {
              const loading = this.$loading({ text: `请稍等...` });
              this.$requestAPI({
                //请求后端地址
                apiUrl:
                  "/mp/e3sh/spareparts/missingDocumentRegistrationService/abolition.do",
                //发送给后端的参数
                variables: { list: this.selectdatas }
              })
                .then(res => {
                  if (res.result === "1") {
                    this.queryTable();
                    this.$message("作废成功!");
                  } else {
                    this.$message(res.msg ? res.msg : "");
                  }
                })
                .catch(err => {
                  if (err.response.data.msg) {
                    this.$message(err.response.data.msg);
                  } else {
                    this.$message(err.message);
                  }
                })
                .finally(() => {
                  loading.close();
                });



            })


          },
          // clickEvent: () => this.editCancel(index),
          text: "作废",
          position: "right",
          component: () => import("@/components/org/linkButton")
        },
        {
          compKey: "btnKey4",
          type: "",
          size: "small",
          name: "reset",
          clickEvent: () => this.reset(),
          text: this.$t("sys.button.reset"),
          position: "right"
        },
        {
          compKey: "btnKey5",
          labelName: "提交",
          size: "small",
          name: "importTemplate",
          icon: "iconfont icon-importTemplate",
          clickEvent: () => {
            const loading = this.$loading({ text: `请稍等...` });
            this.$requestAPI({
              //请求后端地址
              apiUrl:
                "/mp/e3sh/spareparts/missingDocumentRegistrationService/submit.do",
              //发送给后端的参数
              variables: { list: this.selectdatas }
            })
              .then(res => {
                if (res.result === "1") {
                  this.queryTable();
                  this.$message("提交成功!");
                } else {
                  this.$message(res.msg ? res.msg : "");
                }
              })
              .catch(err => {
                if (err.response.data.msg) {
                  this.$message(err.response.data.msg);
                } else {
                  this.$message(err.message);
                }
              })
              .finally(() => {
                loading.close();
              });
          },
          // clickEvent: () => this.editCancel(index),
          text: "提交",
          position: "right",
          component: () => import("@/components/org/linkButton")
        }
        //提交
      ],

      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
              .tableComponents
          : [
              {
                compKey: "compKey1",
                labelName: "审核状态：",
                codeField: "isEnable1",
                component: () => import("@/components/org/LookupValue"),
                oFields: "statusId,statusText",
                options: [
                  { statusId: "PAD001", statusText: "已保存" },
                  { statusId: "PAD002", statusText: "已审核" },
                  { statusId: "PAD003", statusText: "已提交" },
                  { statusId: "PAD004", statusText: "已驳回" },
                  { statusId: "PAD005", statusText: "已作废" }
                ],
                type: "dropdownList",
                isMul: false,
                isMust: true
              },
              {
                compKey: "compKey2",
                labelName: "缺件单号：",
                codeField: "lackPartsCode",
                component: () => import("@/components/org/commonInput"),
                type: "inputText",
                isMul: false,
                isMust: true
              },
              {
                compKey: "compKey3",
                labelName: "VIN：",
                codeField: "vin",
                component: () => import("@/components/org/commonInput"),
                type: "inputText",
                isMul: false,
                isMust: true
              },
              {
                compKey: "compKey4",
                labelName: "车牌号：",
                codeField: "carLicense",
                component: () => import("@/components/org/commonInput"),
                type: "inputText",
                isMul: false,
                isMust: true
              },
              {
                compKey: "compKey5",
                labelName: "登记日期：",
                codeField: "registerDate",
                component: () =>
                  import("@/components/org/datePicker/datePicker"),
                type: "datePicker",
                isMul: false,
                isMust: false
              },

              {
                compKey: "compKey6",
                labelName: "紧急度：",
                codeField: "urgency",
                component: () => import("@/components/org/LookupValue"),
                oFields: "statusId,statusText",
                options: [
                  { statusId: "1", statusText: "紧急" },
                  { statusId: "0", statusText: "一般" }
                ],
                type: "dropdownList",
                isMul: false,
                isMust: false
              },

              {
                compKey: "compKey7",
                labelName: "车型编码：",
                codeField: "bigAreaName7",
                component: () => import("@/components/org/commonInput"),
                type: "inputText",
                isMul: false,
                isMust: false
              },
              {
                compKey: "compKey8",
                labelName: "客户名称：",
                codeField: "customerName",
                component: () => import("@/components/org/commonInput"),
                type: "inputText",
                isMul: false,
                isMust: false
              }
              //   {
              //   compKey: 'compKey4',
              //   labelName: '所属期间：',
              //   codeField: 'bigAreaName3',
              //   component: () => import('@/components/org/datePicker/andtDatePicker'),
              //   type: 'andtDatePicker',
              //   isMul: false,
              //   isMust: true
              // },
            ],

      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
              {
                prop: "releaseId",
                label: "主键ID",
                hidden: true,
                alwaysHidden: true
              },
              {
                prop: "updateControlId",
                label: "并发控制ID",
                hidden: true,
                alwaysHidden: true
              },
              {
                prop: "controlBtn1",
                label: "操作",
                minWidth: 180,
                isComponent: true,
                comps: [
                  {
                    compKey: "propKey1",
                    labelName: "修改",
                    component: () => import("@/components/org/linkButton"),
                    clickEvent: index => this.edit(index)
                    // clickEvent: index =>  this.$message('请选择要修改')

                  }
                  // {
                  //   compKey: "propKey2",
                  //   labelName: "作废",
                  //   component: () => import("@/components/org/linkButton"),
                  //   clickEvent: index => this.editCancel(index)
                  // }
                ]
              },
              {
                prop: "lackPartsCode",
                label: "缺件单号",
                hidden: false
                //   alwaysHidden: true
              },
              {
                prop: "associationTypeName",
                label: "关联类型"
              },
              {
                prop: "associationNo",
                label: "关联单号"
              },
              {
                prop: "carLicense",
                label: "车牌号"
              },
              {
                prop: "vin",
                label: "VIN"
              },
              {
                prop: "carConfigCode",
                label: "车型编码"
              },
              {
                prop: "lackVariety",
                label: "缺件品种数"
              },
              {
                prop: "customerName",
                label: "客户名称"
              },
              {
                prop: "registerPerson",
                label: "登记人员"
              },
              {
                prop: "registerDate",
                label: "登记日期"
              },
              {
                prop: "remark",
                label: "备注"
              },
            {
              prop: "urgencyCn",
              label: "紧急度"
            },
            ],

      // 表单查询数据
      formField: this.$utils.getFormField(
        this,
        {
          isEnable1: "",
          lackPartsCode: "",
          vin: "",
          carLicense: "",
          urgency: "",
          bigAreaName7: "",
          registerDate: "",
          customerName: ""
        },
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
      )
    };
  },

  mounted() {
    // 列表查询
    this.queryTable(1);
    console.log(this.formField)
    // this.$refs.multipleTable.list = [
    //   {'releaseId':'1'}
    // ]
  },

  methods: {
    newlyAdd() {
      this.editPopupsVisible = true;
    },
    // 编辑获取数据
    edit(index) {
      this.codeOpen = 2;
      this.editPopupsVisible = true;
      this.editPopupsState = "edit";
      this.editRowData = this.$utils.deepCopy(
        this.$refs["multipleTable"].list[index]
      );
      console.log(this.editRowData, "this.editRowData");
    },
    // 点击作废
    editCancel(index) {
      this.editPopupsVisible = false;
      this.editRowData = this.$utils.deepCopy(
        this.$refs["multipleTable"].list[index]
      );
      const that = this;
      let formObj = {
        lackPartsId: ""
      };
      formObj.lackPartsId = this.editRowData.lackPartsId;
      const queryObj = {
        // 保存mutation
        type: "mutation",
        // api配置
        apiConfig: orgApis.shortageAuditCancel,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: formObj
      };
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj);
      // 调用中台API方法（可复用）

      this.$confirm('确定要作废吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.$requestAPI(paramD).then(response => {
          if (response.result === "1") {
            this.queryTable();
            this.$message("作废成功");
          } else {
            // 作废失败
            this.$message({
              message: response.msg,
              type: "warn",
              uration: 1000
            });
          }
          this.queryTable(1);
        });
      })
    }
  }
};
</script>
